package com.samxcode.leetcode;

/**
 * Given a linked list, remove the nth node from the end of list and return its head.
 * 
 * @author Sam
 *
 */
public class RemoveNthNode {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode node = head;
        for (int i = 0; i < n; i++) {
            node = node.next;
        }
        if (node == null) {
            return head = head.next;
        }
        ListNode nthPreNode = head;
        while (node.next != null) {
            nthPreNode = nthPreNode.next;
            node = node.next;
        }
        nthPreNode.next = nthPreNode.next.next;
        return head;
    }
}
